<template>
    <div class="editForm">
        <el-form :model="editform2" :label-position="labelPosition" :rules="rules" ref="editform2">
            <div v-if="false">
                <el-input v-model="classCode"></el-input>
            </div>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="editform2.name" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                        <el-radio-group v-model="editform2.sex">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
                        <el-input v-model="editform2.age" type="number" autocomplete="off">
                            <template slot="append">岁</template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="照片" :label-width="formLabelWidth">
                        <el-image style="width: 120px; height: 120px;" :src="`http://39.99.143.137:8000` + editform2.photo"
                            fit="fill"></el-image>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="替换照片" :label-width="formLabelWidth">
                        <el-upload action="#" list-type="picture-card" :on-change="handlePictureCardPreview"
                            :on-remove="handleRemove" :on-exceed="handleExceed" :auto-upload="false" :limit="1">
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible" :modal="false">
                            <el-image width="100%" :src="editform2.dialogImageUrl2" alt="" fit="fill"></el-image>
                        </el-dialog>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="考勤状态" :label-width="formLabelWidth">
                        <el-select v-model="editform2.status" clearable placeholder="请选择">
                            <el-option v-for="item in option" :label="item.label" :key="item.value" :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="班主任" :label-width="formLabelWidth" prop="teacher">
                        <el-input v-model="editform2.teacher" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="班级" :label-width="formLabelWidth" prop="theClass">
                        <el-select v-model="editform2.theClass" clearable placeholder="请选择">
                            <el-option v-for="item in editform2.classMate" :key="item.id" :label="item.text" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="4.8" v-for="(item, index) in editform2.cardList" :key="index">
                    <el-form-item :label="item.label" label-width="120px">
                        <el-input v-model="item.code" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" style="float: left; margin-left: 70px">
            <el-button  @click="gotoCM" type="text" plain>卡号管理</el-button>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closed">取 消</el-button>
            <el-button type="primary" @click="saveEdit('editform2')">提 交</el-button>
        </div>
    </div>
</template>
<script>
    import {
        UPDATE_STUDENT,
        GETCLAZZ
    } from '@/api/api.js'
    export default {
        name: 'editForm',
        props: {
            editform: Object,
            formLabelWidth: String,
            dialogVisible: Boolean,
            dialogImageUrl: String,
            option: Array,
            labelPosition: String,
            editVisible: Boolean,
            getStudent: {
                type: Function,
                default: null
            },
            schoolId: Number,
            getEditForm: Function
        },
        data() {
            return {
                editform2: {
                    id: this.editform.id,
                    name: this.editform.name,
                    sex: this.judgeSex(this.editform.sex),
                    age: this.editform.age,
                    photo: this.editform.photo,
                    status: this.editform.status,
                    teacher: this.editform.teacher,
                    card: this.editform.card,
                    theClass: '',
                    classCode: '',
                    dialogImageUrl2: this.dialogImageUrl,
                    imgFile: '',
                    classMate: [],
                    cardList: [{
                            label: '卡号1',
                            code: ''
                        },
                        {
                            label: '卡号2',
                            code: ''
                        },
                        {
                            label: '卡号3',
                            code: ''
                        },
                        {
                            label: '卡号4',
                            code: ''
                        },
                        {
                            label: '卡号5',
                            code: ''
                        }
                    ],
                },
                editDialogVisible: false,
                rules: {
                    name: [{
                        required: true,
                        message: '请输入学生姓名',
                        trigger: 'blur'
                    }],
                    sex: [{
                        required: true,
                        message: '请选择性别',
                        trigger: 'change'
                    }],
                    age: [{
                        required: true,
                        message: '请输入年龄',
                        trigger: 'blur'
                    }],
                    teacher: [{
                        required: true,
                        message: '请输入班主任姓名',
                        trigger: 'blur'
                    }],
                    theClass: [{
                        required: true,
                        message: '请选择班级',
                        trigger: 'change'
                    }]
                }
            }
        },
        watch: {
            editVisible(n, o) {
                this.close = n;
            },
            editform(n, o) {
                this.editform2.id = n.id
                this.editform2.name = n.name
                this.editform2.sex = this.judgeSex(n.sex)
                this.editform2.age = n.age
                this.editform2.photo = n.photo
                this.editform2.status = n.status
                this.editform2.teacher = n.teacher
                this.editform2.cardList = this.setCard(n.card)
                this.editform2.theClass = null
                // this.classCode = n.classCode
            }
        },
        created() {
            setTimeout(() => {
                this.getClazz()
                this.setCard(this.editform.card)
            }, 100);
        },
        methods: {
            // 查询班级
            async getClazz() {
                await this.$GET(`${GETCLAZZ}`, {
                        schoolId: this.schoolId
                    })
                    .then(res => {
                        if (res.code == 200) {
                            let data = []
                            for (let i = 0; i < res.data.length; i++) {
                                let obj = {}
                                obj.id = res.data[i].classId
                                obj.text = res.data[i].className
                                data[i] = obj
                            }
                            this.editform2.classMate = data
                        }
                    })
            },
            setCard(n) {
                let data = []
                n.forEach((value, index, array) => {
                    data.push({
                        label: `卡号${index + 1}`,
                        code: value.code
                    })
                });
                setTimeout(() => {
                    this.editform2.cardList = data
                }, 100);
            },
            // 保存编辑框
            async saveEdit(formName) {
                let that = this
                that.$refs[formName].validate( async (valid) => {
                    if (valid) {
                        let params = new FormData()
                        params.append("id", that.editform2.id)
                        params.append("name", that.editform2.name)
                        console.log(that.editform2.photo)
                        if (that.editform2.imgFile.raw == undefined || that.editform2.imgFile.raw == "" || that.editform2.imgFile.raw == null) {
                            params.append("photoFile", null)
                        } else {
                            if(that.editform2.imgFile.raw.size < 307200) {
                                params.append("photoFile", that.editform2.imgFile.raw)
                            } else {
                                this.$message.error('请上传小于300kb的照片')
                                return false
                            }
                        }
                        let cardArr = []
                        if (that.cardList < 1) {
                            this.$message.error('请输入至少一个卡号')
                            return false
                        }
                        for (let i = 0; i < that.editform2.cardList.length; i++) {
                            let obj = {}
                            obj.code = that.editform2.cardList[i].code
                            cardArr[i] = obj
                        }
                        params.append("status", that.judgeStatus(that.editform2.status))
                        params.append("age", that.editform2.age)
                        params.append("sex", that.editform2.sex)
                        params.append("teacher", that.editform2.teacher)
                        params.append("theClass", that.editform2.theClass)
                        params.append("classCode", that.editform2.theClass)
                        params.append("cards", JSON.stringify(cardArr))
                        await that.$POST(`${UPDATE_STUDENT}`, params, {
                                header: {
                                    'Content-Type': 'multipart/form-data; charset=utf-8'
                                }
                            })
                            .then(res => {
                                if (res.code == 200) {
                                    that.close = false
                                    that.$emit('toggle-edit', that.close);
                                    that.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    that.editform2.photo = ''
                                    that.getStudent()
                                } else {
                                    that.$message({
                                        message: '修改失败',
                                        type: 'error'
                                    });
                                }
                            })
                    } else {
                        this.$message.error('请正确填写表单')
                    }
                })
            },
            // 上传文件个数超过定义的数量
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
            },
            // 上传照片
            handleRemove(file) {
                console.log(file);
            },
            handlePictureCardPreview(file) {
                if (file.size > 2097152) {
                    this.$message.warning(`文件大小限制为 2MB，请删除后重新上传`)
                    return false;
                }
                this.editform2.dialogImageUrl2 = file.url;
                this.editform2.imgFile = file
                console.log(file)
            },
            // 取消
            closed() {

                this.close = false
                this.$emit('toggle-edit', this.close);

            },
            // 考勤判断
            judgeStatus(status) {
                switch (status) {
                    case 0:
                        return '在校'
                        break;
                    case 1:
                        return '离校'
                        break
                    case 2:
                        return '病假'
                        break
                    case 3:
                        return '缺勤'
                        break
                    case '在校':
                        return 0
                        break;
                    case '离校':
                        return 1
                        break
                    case '病假':
                        return 2
                        break
                    case '缺勤':
                        return 3
                        break
                }
            },
            // 性别判断
            judgeSex(sex) {
                switch (sex) {
                    case 1:
                        return '男'
                        break;
                    case 2:
                        return '女'
                        break;
                    case '男':
                        return 1
                        break;
                    case '女':
                        return 2
                        break;
                }
            },
            // 跳至卡号管理
            gotoCM() {
                this.getEditForm()
                this.$router.push({path: '/CardManage', query: { studentId:  Number(this.editform2.id) }})
            }
        }
    }
</script>
<style lang="scss">
    .dialog-footer {
        text-align: right;
    }
    .cardManage {
        margin-top: 12px;
    }
</style>